package com.scale.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;
import java.util.List;

/**
 * CORS跨域配置类 (备选方案)
 * 
 * 使用说明：
 * 1. 如果WebConfig中的CORS配置不生效，可以启用此配置类
 * 2. 在WebConfig类上添加 @ConditionalOnProperty(name = "cors.config.enabled", havingValue = "false", matchIfMissing = true)
 * 3. 在此类上添加 @ConditionalOnProperty(name = "cors.config.enabled", havingValue = "true")
 * 4. 在application.yml中设置 cors.config.enabled: true 来启用此配置
 * 
 * @author crp
 * @since 2025-09-25
 */
@Configuration
// @ConditionalOnProperty(name = "cors.config.enabled", havingValue = "true")
public class CorsConfig {

    /**
     * CORS配置属性
     */
    @ConfigurationProperties(prefix = "cors")
    public static class CorsProperties {
        
        /**
         * 允许的源列表
         */
        private List<String> allowedOrigins = Arrays.asList(
            "http://localhost:3000",
            "http://127.0.0.1:3000", 
            "http://localhost:3001",
            "http://127.0.0.1:3001", 
            "http://localhost:5173",
            "http://127.0.0.1:5173",
            "http://localhost:8081",
            "http://127.0.0.1:8081"
        );
        
        /**
         * 允许的HTTP方法列表
         */
        private List<String> allowedMethods = Arrays.asList(
            "GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"
        );
        
        /**
         * 允许的请求头列表
         */
        private List<String> allowedHeaders = Arrays.asList(
            "Content-Type",
            "Authorization", 
            "X-Requested-With",
            "Accept",
            "Origin",
            "Cache-Control",
            "X-File-Name",
            "Access-Control-Request-Method",
            "Access-Control-Request-Headers"
        );
        
        /**
         * 暴露的响应头列表
         */
        private List<String> exposedHeaders = Arrays.asList(
            "Content-Type",
            "Authorization",
            "Access-Control-Allow-Origin",
            "Access-Control-Allow-Methods", 
            "Access-Control-Allow-Headers",
            "Access-Control-Max-Age",
            "Content-Disposition",
            "X-Total-Count"
        );
        
        /**
         * 是否允许携带凭证
         */
        private boolean allowCredentials = true;
        
        /**
         * 预检请求缓存时间（秒）
         */
        private long maxAge = 3600;

        // Getters and Setters
        public List<String> getAllowedOrigins() {
            return allowedOrigins;
        }

        public void setAllowedOrigins(List<String> allowedOrigins) {
            this.allowedOrigins = allowedOrigins;
        }

        public List<String> getAllowedMethods() {
            return allowedMethods;
        }

        public void setAllowedMethods(List<String> allowedMethods) {
            this.allowedMethods = allowedMethods;
        }

        public List<String> getAllowedHeaders() {
            return allowedHeaders;
        }

        public void setAllowedHeaders(List<String> allowedHeaders) {
            this.allowedHeaders = allowedHeaders;
        }

        public List<String> getExposedHeaders() {
            return exposedHeaders;
        }

        public void setExposedHeaders(List<String> exposedHeaders) {
            this.exposedHeaders = exposedHeaders;
        }

        public boolean isAllowCredentials() {
            return allowCredentials;
        }

        public void setAllowCredentials(boolean allowCredentials) {
            this.allowCredentials = allowCredentials;
        }

        public long getMaxAge() {
            return maxAge;
        }

        public void setMaxAge(long maxAge) {
            this.maxAge = maxAge;
        }
    }

    /**
     * 配置CORS过滤器 (方式1 - 使用CorsFilter)
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        
        // 允许的源
        config.addAllowedOrigin("http://localhost:3000");
        config.addAllowedOrigin("http://127.0.0.1:3000");
        config.addAllowedOrigin("http://localhost:3001");
        config.addAllowedOrigin("http://127.0.0.1:3001");
        config.addAllowedOrigin("http://localhost:5173");
        config.addAllowedOrigin("http://127.0.0.1:5173");
        config.addAllowedOrigin("http://localhost:8081");
        config.addAllowedOrigin("http://127.0.0.1:8081");
        
        // 允许的HTTP方法
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("PATCH");
        
        // 允许的请求头
        config.addAllowedHeader("*");
        
        // 暴露的响应头
        config.addExposedHeader("Content-Type");
        config.addExposedHeader("Authorization");
        config.addExposedHeader("Access-Control-Allow-Origin");
        config.addExposedHeader("Access-Control-Allow-Methods");
        config.addExposedHeader("Access-Control-Allow-Headers");
        config.addExposedHeader("Access-Control-Max-Age");
        config.addExposedHeader("Content-Disposition");
        config.addExposedHeader("X-Total-Count");
        
        // 允许携带凭证
        config.setAllowCredentials(true);
        
        // 预检请求的缓存时间
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        
        // 配置不同的API路径
        source.registerCorsConfiguration("/api/auth/**", config);       // 认证相关
        source.registerCorsConfiguration("/api/ai-characters/**", config); // 角色管理
        source.registerCorsConfiguration("/api/conversations/**", config);  // 对话管理
        source.registerCorsConfiguration("/api/messages/**", config);      // 消息管理
        source.registerCorsConfiguration("/api/voice/**", config);         // 语音处理
        source.registerCorsConfiguration("/api/user/**", config);          // 用户管理
        source.registerCorsConfiguration("/api/system/**", config);        // 系统配置
        source.registerCorsConfiguration("/api/**", config);               // 通用API路径
        source.registerCorsConfiguration("/voice/**", config);             // 静态资源
        
        return new CorsFilter(source);
    }

    /**
     * 配置CORS源 (方式2 - 提供给Spring Security使用)
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        
        // 允许的源
        configuration.setAllowedOrigins(Arrays.asList(
            "http://localhost:3000",
            "http://127.0.0.1:3000",
            "http://localhost:3001",
            "http://127.0.0.1:3001",
            "http://localhost:5173", 
            "http://127.0.0.1:5173",
            "http://localhost:8081",
            "http://127.0.0.1:8081"
        ));
        
        // 允许的方法
        configuration.setAllowedMethods(Arrays.asList(
            "GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"
        ));
        
        // 允许的请求头
        configuration.setAllowedHeaders(Arrays.asList("*"));
        
        // 暴露的响应头
        configuration.setExposedHeaders(Arrays.asList(
            "Content-Type", "Authorization", "Content-Disposition", "X-Total-Count"
        ));
        
        // 允许凭证
        configuration.setAllowCredentials(true);
        
        // 预检缓存时间
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        
        return source;
    }
}
